import random
import sched
import threading
import time


class SchedulerManager(object):

    def __init__(self):
        self.scheduler = sched.scheduler(time.time, time.sleep)

    def single_scheduler(self, delay=1):
        """
        单次调度实现
        :param delay: 延时时间
        :return:
        """
        self.scheduler.enter(delay, 1, self._single_scheduler, (delay,))
        self.scheduler.run()

    @staticmethod
    def _single_scheduler(delay=0.1):
        """
        单次调度实现
        :param delay: 延时时间
        :return:
        """
        print(f"单次调度执行间隔时间:{delay}")

    def cycle_scheduler(self, multi_thread=False):
        """
        单次调度实现
        :param multi_thread: 多线程，不影响主线程运行
        :return:
        """
        self._cycle_scheduler()
        if multi_thread:
            threading.Thread(target=self.run_scheduler, daemon=True).start()
        else:
            self.run_scheduler()
            # 主线程阻塞

    def _cycle_scheduler(self, delay=10, start_index=1):
        """
        循环调度实现执行
        :param delay: 延时时间
        :param start_index: 开始计数数值
        :return:
        """
        # delay = self.update_scheduler_time()
        print(f"循环调度执行间隔时间:{delay}，任务执行了{start_index}次")
        start_index += 1
        self.scheduler.enter(delay, 1, self._cycle_scheduler, (delay, start_index))

    @staticmethod
    def update_scheduler_time():
        """
        更新循环调度执行时间
        :return:
        """
        return random.random()

    def run_scheduler(self):
        """
        调度执行
        """
        self.scheduler.run()


if __name__ == '__main__':
    scheduler = SchedulerManager()
    # scheduler.single_scheduler()
    scheduler.cycle_scheduler(True)
    print("done")
    scheduler._cycle_scheduler(2, 5000)
    while True:
        pass
